﻿using Microsoft.EntityFrameworkCore;
using System.Reflection;

namespace ED.EFCore
{
    public class EFCoreDBContext : DbContext
    {
        public EFCoreDBContext(DbContextOptions<EFCoreDBContext> options) : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseOpenIddict();
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((a) => a.FullName.Contains("ED.Entity"));
            //if (assemblies == null)
            //{
            //    throw new Exception("数据库实体未配置映射关系");
            //}
            if (assemblies != null)
            {
                foreach (TypeInfo item in assemblies.DefinedTypes)
                {
                    if (item.IsClass && item.ImplementedInterfaces.Any(t => t.Name.Contains("IEntity")) && !item.IsAbstract && !item.IsInterface)
                    {
                        modelBuilder.Model.AddEntityType(item);
                    }
                }
            }

            base.OnModelCreating(modelBuilder);
        }
    }
}
